<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 美食社区</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome -->
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.2/css/all.min.css" rel="stylesheet">
    <link rel="stylesheet" th:href="@{/css/style.css}">
    <link rel="stylesheet" href="/css/layui.css">
    <style>
        .user-table {
            margin-top: 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            border-radius: 8px;
            overflow: hidden;
        }
        /* 移除用户头像样式 */
        .action-buttons .btn {
            margin-right: 5px;
        }
        .modal-body .form-group {
            margin-bottom: 15px;
        }
        .role-badge {
            padding: 5px 10px;
            border-radius: 15px;
            font-size: 12px;
            font-weight: bold;
        }
        .role-admin {
            background-color: #fd7e14;
            color: white;
        }
        .role-user {
            background-color: #28a745;
            color: white;
        }
        .section-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .btn-primary {
            background-color: #fd7e14;
            border-color: #fd7e14;
        }
        .btn-primary:hover {
            background-color: #e76b00;
            border-color: #e76b00;
        }
        .pagination .page-link {
            color: #fd7e14;
        }
        .pagination .active .page-link {
            background-color: #fd7e14;
            border-color: #fd7e14;
        }
    </style>
</head>
<body>

<!-- 引入公共头部 -->
<div th:replace="common/header :: header"></div>

<div class="container mt-5 pt-3">
    <div class="row">
        <div class="col-12">
            <div class="dashboard-card">
                <div class="dashboard-card-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <h2 class="mb-0"><i class="fas fa-users me-2"></i>用户管理</h2>
                        <div class="search-box">
                            <div class="input-group">
                                <input type="text" id="searchInput" class="form-control" placeholder="搜索用户名或昵称...">
                                <button class="btn btn-primary" id="searchBtn">
                                    <i class="fas fa-search"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="dashboard-card-body">
            
            <!-- 用户列表 -->
            <div class="table-responsive user-table">
                <table class="table table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>用户名</th>
                            <th>昵称</th>
                            <th>角色</th>
                            <th>注册时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr th:each="user : ${users}" th:if="${user.username != 'admin'}">
                            <td th:text="${user.username}"></td>
                            <td th:text="${user.nickname}"></td>
                            <td>
                                <span th:class="${user.role == 'admin' ? 'role-badge role-admin' : 'role-badge role-user'}"
                                      th:text="${user.role == 'admin' ? '管理员' : '普通用户'}"></span>
                            </td>
                            <td th:text="${#temporals.format(user.createTime, 'yyyy-MM-dd HH:mm')}"></td>
                            <td class="action-buttons">
                                <button class="btn btn-sm btn-primary edit-user" th:data-id="${user.id}">
                                    <i class="fas fa-edit"></i> 编辑
                                </button>
                                <button class="btn btn-sm btn-danger delete-user" th:data-id="${user.id}" 
                                        th:data-username="${user.username}">
                                    <i class="fas fa-trash-alt"></i> 删除
                                </button>
                            </td>
                        </tr>
                        <tr th:if="${#lists.isEmpty(users) || (#lists.size(users) == 1 && users[0].username == 'admin')}">
                            <td colspan="7" class="text-center py-4">暂无用户数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <!-- 分页 -->
            <nav aria-label="Page navigation" th:if="${totalPages > 1}" class="mt-4">
                <ul class="pagination justify-content-center">
                    <li class="page-item" th:classappend="${currentPage == 1 ? 'disabled' : ''}">
                        <a class="page-link" th:href="@{/admin/users(page=${currentPage - 1})}" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <li class="page-item" th:each="i : ${#numbers.sequence(1, totalPages)}" 
                        th:classappend="${currentPage == i ? 'active' : ''}">
                        <a class="page-link" th:href="@{/admin/users(page=${i})}" th:text="${i}"></a>
                    </li>
                    <li class="page-item" th:classappend="${currentPage == totalPages ? 'disabled' : ''}">
                        <a class="page-link" th:href="@{/admin/users(page=${currentPage + 1})}" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header" style="background-color: #fd7e14; color: white;">
                <h5 class="modal-title" id="editUserModalLabel"><i class="fas fa-user-edit me-2"></i>编辑用户信息</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editUserForm">
                    <input type="hidden" id="userId">
                    <div class="mb-3">
                        <label for="editUsername" class="form-label"><i class="fas fa-user me-1"></i>用户名</label>
                        <input type="text" class="form-control" id="editUsername" readonly>
                    </div>
                    <div class="mb-3">
                        <label for="editNickname" class="form-label"><i class="fas fa-id-badge me-1"></i>昵称</label>
                        <input type="text" class="form-control" id="editNickname" required>
                        <div class="form-text">用户在社区中显示的名称</div>
                    </div>
                    <div class="mb-3">
                        <label for="editBio" class="form-label"><i class="fas fa-info-circle me-1"></i>个人简介</label>
                        <textarea class="form-control" id="editBio" rows="3" placeholder="介绍一下自己吧..."></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="editRole" class="form-label"><i class="fas fa-user-tag me-1"></i>角色</label>
                        <select class="form-select" id="editRole">
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                        </select>
                        <div class="form-text text-warning">请谨慎修改用户角色</div>
                    </div>
                    <div class="mb-3">
                        <label for="editFoodPreference" class="form-label"><i class="fas fa-utensils me-1"></i>食物偏好</label>
                        <input type="text" class="form-control" id="editFoodPreference" placeholder="多个偏好用逗号分隔，如：川菜,甜点,海鲜">
                    </div>
                    <div class="mb-3">
                        <label for="editCookingSkill" class="form-label"><i class="fas fa-cookie me-1"></i>烹饪技能</label>
                        <input type="text" class="form-control" id="editCookingSkill" placeholder="多个技能用逗号分隔，如：炒菜,烘焙,刀工">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal"><i class="fas fa-times me-1"></i>取消</button>
                <button type="button" class="btn btn-primary" id="saveUserBtn"><i class="fas fa-save me-1"></i>保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteUserModal" tabindex="-1" aria-labelledby="deleteUserModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteUserModalLabel"><i class="fas fa-exclamation-triangle text-danger me-2"></i>确认删除</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="text-center mb-3">
                    <i class="fas fa-user-times text-danger fa-3x mb-3"></i>
                    <p>确定要删除用户 <span id="deleteUsername" class="fw-bold"></span> 吗？</p>
                    <p class="text-danger"><small>此操作不可恢复！</small></p>
                </div>
                <input type="hidden" id="deleteUserId">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">确认删除</button>
            </div>
        </div>
    </div>
</div>

<!-- 引入公共底部 -->
<div th:replace="common/footer :: footer"></div>

<!-- jQuery -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Bootstrap Bundle JS -->
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.1/js/bootstrap.bundle.min.js"></script>
<!-- Layui JS -->
<script src="/js/layui.js"></script>
<script>
    $(document).ready(function() {
        // 编辑用户
        $('.edit-user').click(function() {
            const userId = $(this).data('id');
            // 显示加载动画
            const loadingIndex = layui.layer.load(2, {shade: [0.2, '#000']});
            // 获取用户信息
            $.get('/api/admin/user/' + userId, function(response) {
                // 关闭加载动画
                layui.layer.close(loadingIndex);
                if (response.code === 200) {
                    const user = response.data;
                    $('#userId').val(user.id);
                    $('#editUsername').val(user.username);
                    $('#editNickname').val(user.nickname);
                    $('#editBio').val(user.bio);
                    $('#editRole').val(user.role);
                    $('#editFoodPreference').val(user.foodPreference);
                    $('#editCookingSkill').val(user.cookingSkill);
                    $('#editUserModal').modal('show');
                } else {
                    layui.layer.msg('获取用户信息失败: ' + response.msg, {icon: 2});
                }
            }).fail(function() {
                // 关闭加载动画
                layui.layer.close(loadingIndex);
                layui.layer.msg('网络错误，请稍后再试', {icon: 2});
            });
        });
        
        // 保存用户信息
        $('#saveUserBtn').click(function() {
            // 表单验证
            if (!$('#editNickname').val().trim()) {
                layui.layer.msg('昵称不能为空', {icon: 2});
                $('#editNickname').focus();
                return;
            }
            
            const userId = $('#userId').val();
            const userData = {
                nickname: $('#editNickname').val().trim(),
                bio: $('#editBio').val().trim(),
                role: $('#editRole').val(),
                foodPreference: $('#editFoodPreference').val().trim(),
                cookingSkill: $('#editCookingSkill').val().trim()
            };
            
            // 显示加载动画
            const loadingIndex = layui.layer.load(2, {shade: [0.2, '#000']});
            
            $.ajax({
                url: '/api/admin/user/' + userId,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(userData),
                success: function(response) {
                    // 关闭加载动画
                    layui.layer.close(loadingIndex);
                    
                    if (response.code === 200) {
                        $('#editUserModal').modal('hide');
                        
                        // 使用更美观的成功提示窗口
                        layui.layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            area: ['350px', 'auto'],
                            shade: 0.8,
                            id: 'LAY_updateSuccess',
                            btn: ['确定'],
                            btnAlign: 'c',
                            moveType: 1,
                            time: 1500, // 设置1.5秒后自动关闭
                            content: '<div style="padding: 30px; line-height: 22px; background-color: #f8f8f8; color: #555; font-weight: 300; text-align: center;"><i class="fas fa-check-circle" style="font-size: 50px; color: #fd7e14; margin-bottom: 20px; display: block;"></i><div style="font-size: 18px; margin-bottom: 10px; font-weight: bold; color: #333;">更新成功</div><div>用户信息已成功更新</div></div>',
                            success: function(layero){
                                // 添加动画效果
                                $(layero).find('.layui-layer').addClass('layui-anim layui-anim-up');
                            },
                            end: function(){ // 弹窗关闭后刷新页面
                                window.location.reload();
                            },
                            yes: function(index){
                                layui.layer.close(index);
                                window.location.reload();
                            }
                        });
                    } else {
                        layui.layer.msg('更新失败: ' + response.msg, {icon: 2});
                    }
                },
                error: function(xhr) {
                    // 关闭加载动画
                    layui.layer.close(loadingIndex);
                    
                    let errorMsg = '服务器错误，请稍后再试';
                    if (xhr.responseJSON && xhr.responseJSON.msg) {
                        errorMsg = xhr.responseJSON.msg;
                    }
                    layui.layer.msg(errorMsg, {icon: 2});
                }
            });
        });
        
        // 删除用户
        $('.delete-user').click(function() {
            const userId = $(this).data('id');
            const username = $(this).data('username');
            $('#deleteUserId').val(userId);
            $('#deleteUsername').text(username);
            $('#deleteUserModal').modal('show');
        });
        
        // 确认删除
        $('#confirmDeleteBtn').click(function() {
            const userId = $('#deleteUserId').val();
            
            $.ajax({
                url: '/api/admin/user/' + userId,
                type: 'DELETE',
                success: function(response) {
                    if (response.code === 200) {
                        $('#deleteUserModal').modal('hide');
                        // 使用更美观的成功提示窗口
                        layui.layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 0,
                            area: ['350px', 'auto'],
                            shade: 0.8,
                            id: 'LAY_deleteSuccess',
                            btn: ['确定'],
                            btnAlign: 'c',
                            moveType: 1,
                            time: 1500, // 设置1.5秒后自动关闭
                            content: '<div style="padding: 30px; line-height: 22px; background-color: #f8f8f8; color: #555; font-weight: 300; text-align: center;"><i class="fas fa-check-circle" style="font-size: 50px; color: #28a745; margin-bottom: 20px; display: block;"></i><div style="font-size: 18px; margin-bottom: 10px; font-weight: bold; color: #333;">删除成功</div><div>用户已被成功删除</div></div>',
                            success: function(layero){
                                // 添加动画效果
                                $(layero).find('.layui-layer').addClass('layui-anim layui-anim-up');
                            },
                            end: function(){ // 弹窗关闭后刷新页面
                                window.location.reload();
                            },
                            yes: function(index){
                                layui.layer.close(index);
                                window.location.reload();
                            }
                        });
                    } else {
                        layui.layer.msg('删除失败: ' + response.msg, {icon: 2});
                    }
                },
                error: function() {
                    layui.layer.msg('服务器错误，请稍后再试', {icon: 2});
                }
            });
        });
        
        // 搜索功能
        $('#searchBtn').click(function() {
            const keyword = $('#searchInput').val().trim();
            window.location.href = '/admin/users?keyword=' + encodeURIComponent(keyword);
        });
        
        // 回车搜索
        $('#searchInput').keypress(function(e) {
            if (e.which === 13) {
                $('#searchBtn').click();
            }
        });
    });
</script>

</body>
</html>